CREATE PROCEDURE [HaOnAzure].[RemoveDBFromHA]
	@dbName SYSNAME
AS
DECLARE @AccountName NVARCHAR(255);
DECLARE @SharedKey NVARCHAR(4000);

DECLARE @PartitionKey NVARCHAR(260);
DECLARE @RowKey NVARCHAR(260);

SELECT TOP 1 @AccountName = AccountName, @SharedKey = SharedKey 
FROM [HAOnAzure].[Credential] 
WHERE IsMaster = 1;

IF @AccountName IS NULL OR @SharedKey IS NULL
	THROW 53000, 'Default credential not found. Add it and try again.', 1;

DECLARE curs CURSOR FAST_FORWARD FOR
SELECT 
	PartitionKey,
	RowKey
	FROM [SQL2AzureCLR].[Azure].QueryTable(
	@AccountName, @SharedKey, 1,
	'HaOnAzureDatabase', NULL)
	WHERE
		PartitionKey = @dbName;

OPEN curs;
FETCH NEXT FROM curs INTO @PartitionKey, @RowKey
WHILE @@FETCH_STATUS = 0  
BEGIN 
	--PRINT @PartitionKey;
	EXEC [SQL2AzureCLR].[Azure].[DeleteEntity]
		@AccountName, @SharedKey, 1,
		'HaOnAzureDatabase', 
		@PartitionKey, @RowKey;
	FETCH NEXT FROM curs INTO @PartitionKey, @RowKey
END

CLOSE curs;
DEALLOCATE curs;
GO